"use client";
import { Minus, Plus, SearchIcon } from "lucide-react";
import { Button } from "../components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "../components/ui/popover";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "../components/ui/accordion";
import { useCallback, useEffect, useState } from "react";
import { getNodes } from "@/server/flowise/data";

export default function AddNodes() {
    const [keyword, setKeyword] = useState<string>("");
    const [show, setShow] = useState<boolean>(false);
    const [accordionValue, setAccordionValue] = useState<string[]>([]);
    const [originData, setOriginData] = useState<any[]>([]);
    const [items, setItems] = useState<any[]>([]);

    useEffect(() => {
        getNodes().then(res => {
            const originData = res.filter((i: any) => !!!i.tags);
            setOriginData(originData);
            const records = calculateData(originData);
            setItems(records);
        });
    }, []);

    // 计算
    const calculateData = useCallback((list: any[], str?: string) => {
        if (list.length === 0) return [];
        const records: any[] = [];
        const originList = list.filter((i: any) => !str || i.label.toLowerCase().includes(str.toLowerCase()));
        originList.forEach((item: any) => {
            const s = records.find(i => i.category === item.category);
            if (s) {
                s.list.push(item);
            } else {
                records.push({
                    category: item.category,
                    list: [item]
                })
            }
        });
        return records;
    }, [originData]);

    // 拖着开始
    const onDragStart = (event: any, node: any) => {
        event.dataTransfer.setData('application/reactflow', JSON.stringify(node));
        event.dataTransfer.effectAllowed = 'move';
    }

    // 搜索
    const onSearch = (e: any) => {
        const str = e.target.value;
        setKeyword(str);
        const records = calculateData(originData, str);
        setItems(records);
        if(str) {
            setAccordionValue(records.map(i => i.category));
        } else {
            setAccordionValue([]);
        }
    }

    return <>
        <Popover onOpenChange={setShow}>
            <PopoverTrigger asChild>
                <Button size="icon" className="rounded-full shadow-2xl bg-main" title="新增节点" onClick={() => setShow(!show)}>
                    {show ? <Minus className="h-5 w-5 text-white" /> : <Plus className="h-5 w-5 text-white" />}
                </Button>
            </PopoverTrigger>
            <PopoverContent className="w-[345px] overflow-hidden p-0 rounded-md shadow-xl">
                <div className="px-3">
                    <h1 className="font-bold py-2">选择节点</h1>
                    <div className="relative py-2">
                        <input
                            value={keyword}
                            onChange={onSearch}
                            type="search"
                            className="peer block w-full rounded-md border border-gray-200 py-3 pl-10 text-sm outline-2 placeholder:text-gray-500"
                            placeholder="请输入"
                        />
                        <SearchIcon className="absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500" />
                    </div>
                </div>
                <Accordion type="multiple" className="w-full px-5 overflow-auto" value={accordionValue} onValueChange={setAccordionValue} style={{ height: 'calc(100vh - 300px)' }}>
                    {
                        items.map(item => {
                            return <AccordionItem value={item.category} key={item.category}>
                                <AccordionTrigger>{item.category}</AccordionTrigger>
                                <AccordionContent>
                                    {
                                        item.list.map((node: any) => {
                                            return <div
                                                key={node.name}
                                                onDragStart={(event) => onDragStart(event, node)}
                                                draggable
                                                className="flex items-center border-b py-3 px-3 rounded-md cursor-move hover:bg-[#ede7f6]">
                                                <img src={`http://localhost:3000/api/v1/node-icon/${node.name}`} alt="" className="w-10 h-10 mr-3" />
                                                <div className="flex flex-col gap-2">
                                                    <div className="text-base text-black">{node.label}</div>
                                                    <div className="text-sm text-gray-500">{node.description}</div>
                                                </div>
                                            </div>
                                        })
                                    }
                                </AccordionContent>
                            </AccordionItem>
                        })
                    }
                </Accordion>
            </PopoverContent>
        </Popover >
    </>
}